let mongoose = require('mongoose')

const UserSchema = new mongoose.Schema({
  openId: {type: String},
  realName: {type: String},
  mobile: {type: String},
  nickName: {type: String},
  avatar: {type: String},
  sex: {type: String},
  role: [],
  regTime: Date,
  state: Boolean,
  unregTime: Date
})

const User = mongoose.model('user', UserSchema)

module.exports = {
  login: function (code, pswd) {
    return new Promise((resolve, reject) => {
      // 按用户名和密码的方式登录
      User.find({realName: code, mobile: pswd}, function (err, docs) {
        if (err) {
          resolve({success: false, msg: 'mongo find error: ' + err})
        } else if (docs.length === 0) {
          resolve({success: false, msg: '用户名或密码错'})
        } else {
          resolve({success: true, id: docs[0].id, name: docs[0].nickName, avatar: docs[0].avatar, sex: docs[0].sex})
        }
      })
    })
  },
  getUserByOpenId: function (openId) {
    return new Promise((resolve, reject) => {
      // 按openId的方式登录
      User.find({openId: openId}, function (err, docs) {
        if (err) {
          resolve({success: false, msg: 'mongo find error: ' + err})
        } else if (docs.length === 0) {
          resolve({success: false, msg: '无此用户'})
        } else {
          resolve({success: true, id: docs[0].id, name: docs[0].nickName, avatar: docs[0].avatar, sex: docs[0].sex})
        }
      })
    })
  },
  createUser: function (openId, nickName, avatar, sex) {
    let u = new User({
      openId: openId,
      nickName: nickName,
      avatar: avatar,
      sex: sex,
      regTime: new Date(),
      state: true
    })
    return new Promise((resolve, reject) => {
      u.save(function (err, res) {
        if (err) {
          console.log('save user error: ' + err)
          resolve({success: false, msg: 'save user error: ' + err})
        } else {
          resolve({success: true, msg: '保存成功'})
        }
      })
    })
  }
}
